/*
 * @Description: 
 * @Author: YangHeng
 * @Date: 2021-08-09 15:40:20
 * @FilePath: \web_server_app\logger\index.js
 */
const log4js = require('log4js')
const path = require('path')

const default_option = {
  type: civi.isDev ? 'console' : 'dateFile',
  dirname: path.join(civi.RUNTIME_PATH, 'logs/'),
  pattern: 'yyyy-MM-dd.log'
}

const option = Object.assign(default_option, civi.config.log4js)

const configure = {
  replaceConsole: true,
  appenders: {
    // stdout: { type: 'console' },
    debug: {
      type: option.type,
      filename: path.join(option.dirname, 'debug'),
      pattern: option.pattern,
      alwaysIncludePattern: true
    },
    info: {
      type: option.type,
      filename: path.join(option.dirname, 'info'),
      pattern: option.pattern,
      alwaysIncludePattern: true
    },
    warn: {
      type: option.type,
      filename: path.join(option.dirname, 'warn'),
      pattern: option.pattern,
      alwaysIncludePattern: true
    },
    error: {
      type: option.type,
      filename: path.join(option.dirname, 'error'),
      pattern: option.pattern,
      alwaysIncludePattern: true
    },
    fatal: {
      type: option.type,
      filename: path.join(option.dirname, 'fatal'),
      pattern: option.pattern,
      alwaysIncludePattern: true
    },
  },
  categories: {
    debug: { appenders: ['debug'], level: 'debug' },
    default: { appenders: ['info'], level: 'info' },
    info: { appenders: ['info'], level: 'info' },
    warn: { appenders: ['warn'], level: 'warn' },
    error: { appenders: ['error'], level: 'error' },
    fatal: { appenders: ['fatal'], level: 'fatal' },
  }
}


log4js.configure(configure)
civi.logs_history = []


/**
 * @description: 同步日志
 * @param {*} logs
 */
function syncLogs(logs) {
  civi.logs_history.push(logs)
  if (civi.logs_history.length > 200) {
    civi.logs_history.splice(0, civi.logs_history.length - 100)
  }
  // civi.wss && civi.wss.broadcast('logs', logs)
}

module.exports = class {
  static info(...data) {
    var logger = log4js.getLogger('info');
    logger.level = "debug";
    logger.info(...data)
    syncLogs({ type: 'info', data: [...data] })
  }
  static success(...data) {
    var logger = log4js.getLogger('info');
    logger.level = "debug";
    logger.info(...data)
    syncLogs({ type: 'success', data: [...data] })
  }
  static error(...data) {
    var logger = log4js.getLogger('error');
    logger.level = "debug";
    logger.error(...data)
    syncLogs({ type: 'error', data: [...data] })
  }
  static warn(...data) {
    var logger = log4js.getLogger('warn');
    logger.level = "debug";
    logger.warn(...data)
    syncLogs({ type: 'warn', data: [...data] })
  }
  static debug(...data) {
    var logger = log4js.getLogger('debug');
    logger.level = "debug";
    logger.debug(...data)
    syncLogs({ type: 'debug', data: [...data] })
  }
}